<template>
	<div>
		<!--        面包屑导航-->
		<breadcrumb @onNavClick="onNavClickStr" :navData="navData"></breadcrumb>
		<!--        卡片区域-->
		<el-card class="box-card">
			<!--            搜索和添加-->
			<el-row :gutter="20">
				<el-col :span="10">
					<el-input placeholder="请输入内容" v-model="queryInfo.query" class="input-with-select">
						<el-button @click="searchUser" slot="append" icon="el-icon-search"></el-button>
					</el-input>
				</el-col>
				<el-col :span="4">
					<el-button type="primary" @click="addUserVisible = true">添加用户</el-button>
				</el-col>
			</el-row>
			<!--用户列表-->
			<el-table :data="tableData" border >
				<el-table-column label="#" type="index"></el-table-column>
				<el-table-column prop="username" label="姓名"></el-table-column>
				<el-table-column prop="email" label="邮箱"></el-table-column>
				<el-table-column prop="mobile" label="电话"></el-table-column>
				<el-table-column prop="role_name" label="角色"></el-table-column>
				<el-table-column prop="mg_state" label="状态" width="80px">
					<template slot-scope="scope">
						<el-switch @change="onStateChange(scope.row)" v-model="scope.row.mg_state"></el-switch>
					</template>
				</el-table-column>
				<el-table-column prop="date" label="操作">
					<template slot-scope="scope">
						<!--                        修改-->
						<el-button type="primary" size="mini" @click="editUser(scope.row)" icon="el-icon-edit">
						</el-button>
						<!--                        删除-->
						<el-button type="danger" size="mini" @click=onDeleteUser(scope.row) icon="el-icon-delete">
						</el-button>
						<!--                        分配权限-->
						<el-tooltip class="item" effect="dark" content="分配角色" placement="top">
							<el-button @click="assignRoles(scope.row)" type="warning" size="mini"
								icon="el-icon-setting"></el-button>
						</el-tooltip>
					</template>
				</el-table-column>
			</el-table>
			<!--            分页-->
			<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
				:current-page="queryInfo.pagenum" :page-sizes="[1, 2, 5, 10]" :page-size="queryInfo.pagesize"
				layout="total, sizes, prev, pager, next, jumper" :total="total">
			</el-pagination>

		</el-card>



		<!--        添加用户-->
		<el-dialog title="添加用户" :visible.sync="addUserVisible">
			<el-form :model="addUser" :rules="addUserRules" ref="addUserRuleForm" label-width="100px">
				<el-form-item label="用户名" prop="username">
					<el-input v-model="addUser.username"></el-input>
				</el-form-item>
				<el-form-item label="密码" prop="password">
					<el-input v-model="addUser.password"></el-input>
				</el-form-item>
				<el-form-item label="邮箱" prop="email">
					<el-input v-model="addUser.email"></el-input>
				</el-form-item>
				<el-form-item label="电话" prop="mobile">
					<el-input v-model="addUser.mobile"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="addUserVisible = false">取 消</el-button>
				<el-button type="primary" @click="onAddUser">确 定</el-button>
			</div>
		</el-dialog>
		<!--修改用户对话框-->
		<el-dialog title="编辑用户" :visible.sync="editDialogVisible" width="60%">
			<el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="100px">
				<!--用户名-->
				<el-form-item label="用户名">
					<el-input disabled v-model="editForm.username"></el-input>
				</el-form-item>
				<!--邮箱-->
				<el-form-item label="邮箱" prop="email">
					<el-input v-model="editForm.email"></el-input>
				</el-form-item>
				<!--电话-->
				<el-form-item label="电话" prop="mobile">
					<el-input v-model="editForm.mobile"></el-input>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="editDialogVisible= false">取 消</el-button>
				<el-button type="primary" @click="onEditBtnClick">确 定</el-button>
			</span>
		</el-dialog>
		<!--分配角色对话框-->
		<el-dialog title="分配角色" :visible.sync="rolesDialogVisible" width="60%">
			<el-form :model="rolesForm" ref="rolesFormRef" label-width="100px">
				<!--用户名-->
				<el-form-item label="当前的用户:">
					<span>{{rolesForm.username}}</span>
					<!--<el-input disabled v-model="rolesForm.username"></el-input>-->
				</el-form-item>
				<!--角色-->
				<el-form-item label="当前的角色:">
					<span>{{rolesForm.role_name}}</span>
					<!--<el-input v-model="rolesForm.role_name"></el-input>-->
				</el-form-item>
				<!--新角色-->
				<el-form-item label="分配新角色:">
					<el-select v-model="rolesForm.rid" placeholder="请选择">
						<el-option v-for="item in rolesOptions" :key="item.id" :label="item.roleName" :value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="rolesDialogVisible= false">取 消</el-button>
				<el-button type="primary" @click="onAssignRolesBtnClick">确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	import http from "../../http/api.js";

	export default {
		created() {
			this.getUserList()
		},
		name: "Users",
		data() {
			let checkEmail = async (rule, value, callback) => {
				let reg = /^[0-9|A-z|_]{1,17}[@][0-9|A-z]{1,3}.(com)$/;
				if (reg.test(value)) {
					return callback();
				} else {
					return callback(new Error('请输入正确的邮箱'));
				}
			};
			let checkMobile = (rule, value, callback) => {
				let reg = /^1[3|4|5|7|8][0-9]{9}$/;
				if (reg.test(value)) {
					return callback();
				} else {
					return callback(new Error('请输入正确的电话号码'));
				}
			};


			return {
				//查询用户信息的参数
				queryInfo: {
					query: "",
					pagenum: 1,
					pagesize: 10,
				},
				//总条数
				total: 0,
				navData: [
					"用户管理",
					"用户列表"
				],
				tableData: [],
				addUserVisible: false,
				addUser: {
					username: "",
					password: "",
					email: "",
					mobile: ""
				},
				//添加用户表单验证
				addUserRules: {
					username: [{
							required: true,
							message: '请输入用户名称',
							trigger: 'blur'
						},
						{
							min: 5,
							max: 8,
							message: '长度在 5 到 8 个字符',
							trigger: 'blur'
						}
					],
					password: [{
							required: true,
							message: '请输入密码',
							trigger: 'blur'
						},
						{
							min: 5,
							max: 8,
							message: '长度在 5 到 8 个字符',
							trigger: 'blur'
						}
					],
					email: [{
							required: true,
							message: '请输入邮箱',
							trigger: 'blur'
						},
						{
							validator: checkEmail,
							trigger: 'blur'
						}
					],
					mobile: [{
							required: true,
							message: '请输入电话',
							trigger: 'blur'
						},
						{
							validator: checkMobile,
							trigger: 'blur'
						}
					],
				},
				editDialogVisible: false,
				//编辑用户表单
				editForm: {
					username: "",
					email: "",
					mobile: ""
				},
				editRules: {
					email: [{
							required: true,
							message: '请输入邮箱',
							trigger: 'blur'
						},
						{
							type: 'email',
							message: '请输入正确的邮箱地址',
							trigger: 'blur'
						}
					],
					mobile: [{
							required: true,
							message: '请输入电话号码',
							trigger: 'blur'
						},
						{
							validator: checkMobile,
							message: '请输入正确的电话号码',
							trigger: 'blur'
						}
					],
				},
				curEditId: "",
				//分配角色
				rolesDialogVisible: false,
				rolesForm: {
					userId: "",
					username: "",
					role_name: "",
					rid: "",
				},
				rolesOptions: []
			}
		},
		methods: {
			onNavClickStr(str) {
				console.log(str);
			},
			//获取用户列表
			async getUserList() {
				let {
					data: res
				} = await this.$http.get("users", {
					params: this.queryInfo
				})
				if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
				this.total = res.data.total;
				this.tableData = res.data.users;

			},
			//查询用户信息
			searchUser() {
				this.queryInfo.pagenum = 1;
				this.getUserList();
			},
			handleSizeChange(val) {
				this.queryInfo.pagesize = val;
				this.getUserList();
			},
			handleCurrentChange(val) {
				this.queryInfo.pagenum = val;
				this.getUserList();
			},
			//切换用户状态
			async onStateChange(row) {
				let {
					data: res
				} = await this.$http.put(`users/${row.id}/state/${row.mg_state}`);
				if (res.meta.status !== 200) {
					row.mg_state = !row.mg_state;
					return this.$message.error(res.meta.msg);
				}
				this.$message.success(res.meta.msg);
			},
			//确定添加用户
			onAddUser() {
				this.$refs.addUserRuleForm.validate(async (valid) => {
					if (!valid) return;
					let {
						data: res
					} = await this.$http.post("users", this.addUser);
					if (res.meta.status !== 201) return this.$message.error(res.meta.msg);
					this.getUserList()
					this.$message.success(res.meta.msg);
					this.addUserVisible = false;
				})
			},
			//删除用户
			async onDeleteUser(row) {
				let result = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).catch(err => err);
				if (result !== "confirm") return this.$message.info("取消删除")
				let {
					data: res
				} = await this.$http.delete(`users/${row.id}`)
				if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
				this.getUserList()
				this.$message.success(res.meta.msg);
			},
			//编辑用户
			editUser(item) {
				this.curEditId = item.id;
				this.editForm.username = item.username;
				this.editForm.email = item.email;
				this.editForm.mobile = item.mobile;
				this.editDialogVisible = true;
			},
			//点击确定修改
			onEditBtnClick() {
				this.$refs.editFormRef.validate((value) => {
					if (!value) return;
					this.$http.put(`users/${this.curEditId}`, this.editForm).then((res) => {
						let data = res.data;
						if (data.meta.status === 200) {
							this.getUserList();
							this.$message.success(data.meta.msg);
							this.editDialogVisible = false;
						} else {
							this.$message.error(data.meta.msg);
						}
					})

				})
			},
			//分配角色
			assignRoles(item) {
				this.rolesForm.userId = item.id;
				this.rolesForm.username = item.username;
				this.rolesForm.role_name = item.role_name;
				this.rolesForm.rid = "";
				this.$http.get("roles").then((res) => {
					console.log(res.data);
					this.rolesOptions = res.data.data;
					this.rolesDialogVisible = true;
				});
			},
			onAssignRolesBtnClick() {
				let rid = this.rolesForm.rid;
				if (!rid) {
					return this.$message.warning("请选择要分配的新角色！")
				}
				this.$http.put(`users/${this.rolesForm.userId}/role`, {
					rid
				}).then((res) => {
					let data = res.data;
					if (data.meta.status === 200) {
						this.getUserList();
						this.$message.success(data.meta.msg);
						this.rolesDialogVisible = false;
					} else {
						this.$message.error(data.meta.msg);
					}
				})
			}
		}
	}
</script>

<style scoped>

</style>
